#!/bin/bash
###############################################################################
# @用例ID: 20230528-141338-315009951
# @用例名称: cpio
# @用例级别: 3
# @用例标签:
# @用例类型: 功能
###############################################################################
[ -z "$TST_TS_TOPDIR" ] && {
    TST_TS_TOPDIR="$(realpath "$(dirname "$0")/..")"
    export TST_TS_TOPDIR
}
source "${TST_TS_TOPDIR}/tst_common/lib/common.sh" || exit 1
###############################################################################

g_tmpdir="$(mktemp -d)"


tc_setup() {
    msg "this is tc_setup"
    # @预置条件:系统正常运行，且已安装 cpio
    assert_true yum install -y cpio

    # @预置条件:
    return 0
}

do_test() {
    msg "this is do_test"

    # 创建一个临时目录
    tmpdir="$(mktemp -d)"

    # 在临时目录中创建一些文件和目录
    mkdir "${tmpdir}/dir1"
    echo "This is file1" > "${tmpdir}/dir1/file1.txt"
    mkdir "${tmpdir}/dir2"
    echo "This is file2" > "${tmpdir}/dir2/file2.txt"

    # @测试步骤:1 创建 cpio 归档文件
    # @预期结果:1 确保成功创建 cpio 归档文件
    find "${tmpdir}" | cpio -o > "${tmpdir}/archive.cpio"
    if [ $? -eq 0 ]; then
        echo "CPIO archive creation successful"
    else
        echo "CPIO archive creation failed"
        return 1
    fi

    # @测试步骤:2 解压 cpio 归档文件
    # @预期结果:2 确保成功解压 cpio 归档文件并恢复原始文件和目录
    mkdir "${tmpdir}/extract"
    cd "${tmpdir}/extract"
    cpio -i < "${tmpdir}/archive.cpio"
    if [ $? -eq 0 ]; then
        echo "CPIO archive extraction successful"
    else
        echo "CPIO archive extraction failed"
        return 1
    fi

    # 验证解压后的文件和目录是否正确恢复
    if [ -f "${tmpdir}/extract/dir1/file1.txt" ] && [ -f "${tmpdir}/extract/dir2/file2.txt" ]; then
        echo "Files and directories successfully restored"
    else
        echo "File and directory restoration failed"
        return 1
    fi

    # @测试步骤:3 使用 cpio 命令列出归档文件内容
    # @预期结果:3 确保成功列出归档文件中的文件和目录列表
    cpio -it < "${tmpdir}/archive.cpio" | grep -E "dir1|dir2"
    if [ $? -eq 0 ]; then
        echo "CPIO archive content listing successful"
    else
        echo "CPIO archive content listing failed"
        return 1
    fi

    return 0
}



tc_teardown() {
    msg "this is tc_teardown"
    # 清理临时目录
    assert_true rm -rf "${tmpdir}"
    rm -rfv "$g_tmpdir" || return 1
    return 0
}

###############################################################################
tst_main "$@"
###############################################################################
